package edu.thu.studio.ormdesigner.model.orm.table;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

import edu.thu.studio.ormdesigner.model.AbstractObjectModel;
import edu.thu.studio.ormdesigner.util.Properties;
import edu.thu.studio.ormdesigner.util.Utils;

@XStreamAlias("table")
public class Table extends AbstractObjectModel {

	private static final long serialVersionUID = 6998985022414351214L;

	@XStreamAlias("references")
	private ReferenceSet references = new ReferenceSet();

	@XStreamAlias("key")
	private Key key;

	@XStreamAlias("columns")
	private ColumnSet columns = new ColumnSet();

	@XStreamAsAttribute
	@XStreamAlias("generate-code")
	private Boolean generateCode = true;

	public Table() {
	}

	public ReferenceSet getReferences() {
		return references;
	}

	public void setReferences(ReferenceSet references) {
		this.references = references;
	}

	public Key getKey() {
		return key;
	}

	public void setKey(Key key) {
		this.key = key;
	}

	public ColumnSet getColumns() {
		return columns;
	}

	public void setColumns(ColumnSet columns) {
		this.columns = columns;
	}

	public Boolean getGenerateCode() {
		return generateCode;
	}

	public void setGenerateCode(Boolean generateCode) {
		this.generateCode = generateCode;
	}

	public boolean isReferable() {
		if (null != this.key) {
			return true;
		}

		for (Column column : this.columns) {
			if (column.getPrimary()) {
				return true;
			}
		}

		return false;
	}

	public void checkAndInit() {
		if (null == id) {
			id = Utils.getUUID();
		}
		if (null == code) {
			code = Properties.editor_new_table_code;
		}
		if (null == name) {
			name = Properties.editor_new_table_name;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Table clone() {
		Table clone = (Table) super.clone();
		clone.columns = (ColumnSet) columns.clone();
		if (null != key) {
			clone.key = (Key) key.clone();
		}
		clone.setGenerateCode(true);
		clone.setStereotype("");
		clone.references = (ReferenceSet) references.clone();

		return clone;
	}

}
